package com.huawei.fastengine.internal;

import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
import com.huawei.fastengine.fastview.Config;
import com.huawei.fastengine.fastview.download.utils.CheckUtils;
import com.huawei.fastengine.fastview.download.utils.log.FastViewLogUtils;
import com.huawei.fastsdk.IFastSDKProxy;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DnsConfig;
import dalvik.system.BaseDexClassLoader;
import dalvik.system.PathClassLoader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class FastSdkLoader {
    private static FastSdkLoader instance;
    AssetManager mAssetManager;
    private BaseDexClassLoader mFastSDKDex;
    private IFastSDKProxy mFastSDKProxy;
    private HostMode mHostMode = HostMode.Full;

    static class FastSdkClassLoader extends ClassLoader {
        private static final Set<String> CLASS_SET = new HashSet(Arrays.asList(CLASS_VALUES));
        private static final String[] CLASS_VALUES = new String[]{"com.huawei.fastsdk.IFastSDKProxy", "com.huawei.fastsdk.IFastSDKInstance", "com.huawei.fastsdk.IFastRenderListener", "com.huawei.fastsdk.IFastCardMessage"};
        private static final String TAG = "FastSdkClassLoader";
        private ClassLoader mAppClassLoader;

        public FastSdkClassLoader(ClassLoader classLoader, ClassLoader classLoader2) {
            super(classLoader);
            this.mAppClassLoader = classLoader2;
        }

        protected Class<?> findClass(String str) throws ClassNotFoundException {
            Class<?> cls = null;
            if (!(str == null || this.mAppClassLoader == null || !CLASS_SET.contains(str))) {
                cls = this.mAppClassLoader.loadClass(str);
                if (cls == null) {
                    Log.e(TAG, "ERROR,Class is missing in host app: " + str);
                }
            }
            return cls == null ? super.findClass(str) : cls;
        }
    }

    public enum HostMode {
        Full,
        Lite,
        ShareLibrary
    }

    private FastSdkLoader(Application application, HostMode hostMode, ArrayList<String> arrayList, ArrayList<String> arrayList2) throws NameNotFoundException, IllegalAccessException {
        try {
            String str;
            String str2;
            this.mHostMode = hostMode;
            if (hostMode == HostMode.Full) {
                str = null;
            } else {
                ApplicationInfo applicationInfo = application.getPackageManager().getPackageInfo(Config.FASTAPP_PACKAGE_NAME, DnsConfig.MAX_CACHE_ENTRIES).applicationInfo;
                String str3 = applicationInfo.sourceDir;
                str2 = applicationInfo.nativeLibraryDir;
                if (hostMode == HostMode.Lite) {
                    if (CheckUtils.isCorrectSign(application, Config.FASTAPP_PACKAGE_NAME)) {
                        this.mFastSDKDex = new PathClassLoader(str3, applicationInfo.nativeLibraryDir, new FastSdkClassLoader(application.getClassLoader().getParent(), application.getClassLoader()));
                        addResourcesPath(application, str3);
                    } else {
                        throw new IllegalAccessException("FastAPP signature illegal");
                    }
                }
                str = str2;
            }
            this.mFastSDKProxy = (IFastSDKProxy) createObject("com.huawei.fastsdk.FastSDKProxy", null, new Object[0]);
            if (this.mFastSDKProxy == null) {
                throw new IllegalAccessException("Instantiate the FastSDK failed");
            } else if (TextUtils.isEmpty(str)) {
                this.mFastSDKProxy.init(application, str, arrayList, arrayList2);
            } else {
                FastViewLogUtils.e("FastSDKEngine", "dong libraryDir " + str);
                if (str.startsWith("/data") || HostMode.ShareLibrary != hostMode) {
                    FastViewLogUtils.e("FastSDKEngine", "libraryDirnew ");
                    this.mFastSDKProxy.init(application, str, arrayList, arrayList2);
                    return;
                }
                Log.i("FastSdkLoader", "initialize copy so");
                str2 = application.getApplicationInfo().dataDir + "/cache/lib";
                FastViewLogUtils.e("FastSDKEngine", "libraryDir " + str2);
                this.mFastSDKProxy.init(application, str2, arrayList, arrayList2);
            }
        } catch (NameNotFoundException e) {
            throw new NameNotFoundException("FastEngine is not installed");
        } catch (UnsatisfiedLinkError e2) {
            throw new UnsatisfiedLinkError();
        }
    }

    private void addResourcesPath(Context context, String str) {
        try {
            this.mAssetManager = context.getAssets();
            AssetManager.class.getDeclaredMethod("addAssetPath", new Class[]{String.class}).invoke(context.getAssets(), new Object[]{str});
        } catch (Throwable th) {
            FastViewLogUtils.e("FastSdkLoader", "addResourcesPath Exception!");
        }
    }

    private Object createObject(String str, Class<?>[] clsArr, Object... objArr) {
        try {
            Class cls;
            if (this.mHostMode != HostMode.Lite) {
                cls = Class.forName(str);
            } else if (this.mFastSDKDex == null) {
                return null;
            } else {
                cls = this.mFastSDKDex.loadClass(str);
            }
            return cls.getDeclaredConstructor(clsArr).newInstance(objArr);
        } catch (ClassNotFoundException e) {
            FastViewLogUtils.e("FastSdkLoader", "ClassNotFoundException!");
            return null;
        } catch (NoSuchMethodException e2) {
            FastViewLogUtils.e("FastSdkLoader", "NoSuchMethodException!");
            return null;
        } catch (InstantiationException e3) {
            FastViewLogUtils.e("FastSdkLoader", "InstantiationException!");
            return null;
        } catch (IllegalAccessException e4) {
            FastViewLogUtils.e("FastSdkLoader", "IllegalAccessException!");
            return null;
        } catch (InvocationTargetException e5) {
            FastViewLogUtils.e("FastSdkLoader", "InvocationTargetException!");
            return null;
        }
    }

    public static synchronized void destroy(boolean z) {
        synchronized (FastSdkLoader.class) {
            if (instance != null) {
                instance.destroyInternal(z);
                instance = null;
            }
        }
    }

    public static synchronized FastSdkLoader getInstance() {
        FastSdkLoader fastSdkLoader;
        synchronized (FastSdkLoader.class) {
            fastSdkLoader = instance;
        }
        return fastSdkLoader;
    }

    private Field getResources(Class cls) {
        Field field = null;
        while (cls != null && field == null) {
            try {
                field = cls.getDeclaredField("mResources");
            } catch (NoSuchFieldException e) {
                FastViewLogUtils.e("FastSdkLoader", "NoSuchFieldException!");
            }
            cls = cls.getSuperclass();
        }
        return field;
    }

    public static synchronized void init(Application application, HostMode hostMode, ArrayList<String> arrayList, ArrayList<String> arrayList2) throws NameNotFoundException, IllegalAccessException, UnsatisfiedLinkError {
        synchronized (FastSdkLoader.class) {
            if (instance == null) {
                instance = new FastSdkLoader(application, hostMode, arrayList, arrayList2);
            }
        }
    }

    public void destroyInternal(boolean z) {
        if (this.mFastSDKProxy != null) {
            this.mFastSDKProxy.destroy(z);
            this.mFastSDKProxy = null;
        }
    }

    public IFastSDKProxy getFastSDKProxy() {
        return this.mFastSDKProxy;
    }

    public HostMode getHostMode() {
        return this.mHostMode;
    }

    public void patchResources(Context context) {
        if (this.mHostMode == HostMode.Lite) {
            try {
                final Field resources = getResources(context.getClass());
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        resources.setAccessible(true);
                        return null;
                    }
                });
                Resources resources2 = new Resources(this.mAssetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration());
                resources2.newTheme().setTo(context.getTheme());
                resources.set(context, resources2);
            } catch (IllegalAccessException e) {
                FastViewLogUtils.e("FastSdkLoader", "IllegalAccessException!");
            } catch (Exception e2) {
                FastViewLogUtils.e("FastSdkLoader", "Exception!");
            }
        }
    }
}
